//
//  NSMutableAttributedString+MHMoment.m
// MiaoCircle
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "NSMutableAttributedString+MHMoment.h"
#import "MHMomentHelper.h"
#import "MHEmoticonManager.h"
#import "MHStatusHelper.h"
@implementation NSMutableAttributedString (MHMoment)

//- (void)mh_regexContentWithWithEmojiImageFontSize:(CGFloat)fontSize{
//}

- (void)mh_regexContentWithWithEmojiImageFontSize:(CGFloat)fontSize{
    
    /// 高亮背景
    YYTextBorder *border = [YYTextBorder new];
    border.cornerRadius = 0;
    border.insets = UIEdgeInsetsMake(0, -1, 0, -1);
    border.fillColor = MHMomentTextHighlightBackgroundColor;
    
    /// 匹配链接
    NSArray<NSTextCheckingResult *> *linkUrlResults = [[MHMomentHelper regexLinkUrl] matchesInString:self.string options:kNilOptions range:self.yy_rangeOfAll];
    for (NSTextCheckingResult *link in linkUrlResults) {
        if (link.range.location == NSNotFound && link.range.length <= 1) continue;
        if ([self yy_attribute:YYTextHighlightAttributeName atIndex:link.range.location] == nil) {
            [self yy_setColor:MHMomentContentUrlTextColor range:link.range];
            /// 匹配userInfo
            /// 点击高亮
            YYTextHighlight *highlight = [YYTextHighlight new];
            // 将用户数据带出去
            highlight.userInfo = @{MHMomentLinkUrlKey:[self.string substringWithRange:link.range]};
            [highlight setBackgroundBorder:border];
            [self yy_setTextHighlight:highlight range:link.range];
        }
    }
    
    
    /// 匹配电话号码
//    NSArray<NSTextCheckingResult *> *phoneResults = [[MHMomentHelper regexPhoneNumber] matchesInString:self.string options:kNilOptions range:self.string.rangeOfAll];
//
//    for (NSTextCheckingResult *phone in phoneResults) {
//        if (phone.range.location == NSNotFound && phone.range.length <= 1) continue;
//        if ([self yy_attribute:YYTextHighlightAttributeName atIndex:phone.range.location] == nil) {
//            [self yy_setColor:MHMomentContentUrlTextColor range:phone.range];
//            /// 匹配userInfo
//            /// 点击高亮
//            YYTextHighlight *highlight = [YYTextHighlight new];
//            // 将用户数据带出去
//            highlight.userInfo = @{MHMomentPhoneNumberKey:[self.string substringWithRange:phone.range]};
//            [highlight setBackgroundBorder:border];
//            [self yy_setTextHighlight:highlight range:phone.range];
//        }
//    }
    
    
    {
        static NSArray *topicExts, *topicExtImages;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
//            topicExts = @[ @"[电影]#", @"[图书]#", @"[音乐]#", @"[地点]#", @"[股票]#" ];
//            topicExtImages = @[
//                               //                [MHStatusHelper imageNamed:@"timeline_card_small_movie"],
//                               //                [MHStatusHelper imageNamed:@"timeline_card_small_book"],
//                               //                [MHStatusHelper imageNamed:@"timeline_card_small_music"],
//                               //                [MHStatusHelper imageNamed:@"timeline_card_small_location"],
//                               //                [MHStatusHelper imageNamed:@"timeline_card_small_stock"]
//                               ];
//        });
            topicExts = @[]; // @[ @"[微信]#", @"[附近]#", @"[圈内]#" ];
            topicExtImages = @[]; //@[
//                               [UIImage imageNamed:@"ic_theme_fx"],
//                               [UIImage imageNamed:@"ic_theme_fj"],
//                               [UIImage imageNamed:@"ic_theme_qn"],
////                               [MHStatusHelper imageNamed:@"timeline_card_small_location"],
////                               [MHStatusHelper imageNamed:@"timeline_card_small_stock"]
//                               ];
        });

        
        
        NSArray<NSTextCheckingResult *> *topicResults = [[MHStatusHelper regexTopic] matchesInString:self.string options:kNilOptions range:self.yy_rangeOfAll];
        NSUInteger clipLength = 0;
        for (NSTextCheckingResult *topic in topicResults) {
            if (topic.range.location == NSNotFound && topic.range.length <= 1) continue;
            NSRange range = topic.range;
            range.location -= clipLength;
            
            __block BOOL containsBindingRange = NO;
            [self enumerateAttribute:YYTextBindingAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
                if (value) {
                    containsBindingRange = YES;
                    *stop = YES;
                }
            }];
            if (containsBindingRange) continue;
            
            BOOL hasExt = NO;
            NSString *subText = [self.string substringWithRange:range];
            for (NSUInteger i = 0; i < topicExts.count; i++) {
                NSString *ext = topicExts[i];
                if ([subText hasSuffix:ext] && subText.length > ext.length + 1) {
                    
                    NSMutableAttributedString *replace = [[NSMutableAttributedString alloc] initWithString:[subText substringWithRange:NSMakeRange(1, subText.length - 1 - ext.length)]];
                    NSAttributedString *pic = [self _attachmentWithFontSize:fontSize image:topicExtImages[i] shrink:YES];
                    [replace insertAttributedString:pic atIndex:0];
                    replace.yy_font = MHRegularFont(fontSize);
                    replace.yy_color = MH_TAG_TEXT_COLOR;
                    
                    // original text, used for text copy
                    YYTextBackedString *backed = [YYTextBackedString stringWithString:subText];
                    
                    [replace yy_setTextBackedString:backed range:NSMakeRange(0, replace.length)];
                    
                    [self replaceCharactersInRange:range withAttributedString:replace];
                    [self yy_setTextBinding:[YYTextBinding bindingWithDeleteConfirm:YES] range:NSMakeRange(range.location, replace.length)];
//                    if (selectedRange) {
//                        *selectedRange = [self _replaceTextInRange:range withLength:replace.length selectedRange:*selectedRange];
//                    }
                    
                    clipLength += range.length - replace.length;
                    hasExt = YES;
                    break;
                }
            }
            
            if (!hasExt) {
                [self yy_setColor:MH_TAG_TEXT_COLOR range:range];
            }
        }
        
    }
    
    
    {
        NSArray<NSTextCheckingResult *> *emoticonResults = [[MHStatusHelper regexEmoticon] matchesInString:self.string options:kNilOptions range:self.yy_rangeOfAll];
        NSUInteger clipLength = 0;
        for (NSTextCheckingResult *emo in emoticonResults) {
            if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
            NSRange range = emo.range;
            range.location -= clipLength;
            if ([self yy_attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
            NSString *emoString = [self.string substringWithRange:range];
            NSString *imagePath = [MHStatusHelper emoticonDic][emoString];
            UIImage *image = [MHStatusHelper imageWithPath:imagePath];
            if (!image) continue;
            
            __block BOOL containsBindingRange = NO;
            [self enumerateAttribute:YYTextBindingAttributeName inRange:range options:NSAttributedStringEnumerationLongestEffectiveRangeNotRequired usingBlock:^(id value, NSRange range, BOOL *stop) {
                if (value) {
                    containsBindingRange = YES;
                    *stop = YES;
                }
            }];
            if (containsBindingRange) continue;
            
            
            YYTextBackedString *backed = [YYTextBackedString stringWithString:emoString];
            NSMutableAttributedString *emoText = [NSAttributedString yy_attachmentStringWithEmojiImage:image fontSize:fontSize].mutableCopy;
            // original text, used for text copy
            [emoText  yy_setTextBackedString:backed range:NSMakeRange(0, emoText.length)];
            [emoText yy_setTextBinding:[YYTextBinding bindingWithDeleteConfirm:NO] range:NSMakeRange(0, emoText.length)];
            
            [self replaceCharactersInRange:range withAttributedString:emoText];
            
//            if (selectedRange) {
//                *selectedRange = [self _replaceTextInRange:range withLength:emoText.length selectedRange:*selectedRange];
//            }
            clipLength += range.length - emoText.length;
        }
    }
    
    //// 匹配表情
    NSArray<NSTextCheckingResult *> *emoticonResults = [[MHEmoticonManager regexEmoticon] matchesInString:self.string options:kNilOptions range:self.yy_rangeOfAll];
    NSUInteger emoClipLength = 0;
    for (NSTextCheckingResult *emo in emoticonResults) {
        if (emo.range.location == NSNotFound && emo.range.length <= 1) continue;
        
        NSRange range = emo.range;
        range.location -= emoClipLength;
        if ([self yy_attribute:YYTextHighlightAttributeName atIndex:range.location]) continue;
        if ([self yy_attribute:YYTextAttachmentAttributeName atIndex:range.location]) continue;
        NSString *emoString = [self.string substringWithRange:range];
        NSString *imagePath = [MHEmoticonManager emoticonDic][emoString];
        UIImage *image = [MHEmoticonManager imageWithPath:imagePath];
        if (!image) continue;
        NSAttributedString *emoText = [NSAttributedString yy_attachmentStringWithEmojiImage:image fontSize:fontSize];
        [self replaceCharactersInRange:range withAttributedString:emoText];
        emoClipLength += range.length - 1;
    }
}

// correct the selected range during text replacement
- (NSRange)_replaceTextInRange:(NSRange)range withLength:(NSUInteger)length selectedRange:(NSRange)selectedRange {
    // no change
    if (range.length == length) return selectedRange;
    // right
    if (range.location >= selectedRange.location + selectedRange.length) return selectedRange;
    // left
    if (selectedRange.location >= range.location + range.length) {
        selectedRange.location = selectedRange.location + length - range.length;
        return selectedRange;
    }
    // same
    if (NSEqualRanges(range, selectedRange)) {
        selectedRange.length = length;
        return selectedRange;
    }
    // one edge same
    if ((range.location == selectedRange.location && range.length < selectedRange.length) ||
        (range.location + range.length == selectedRange.location + selectedRange.length && range.length < selectedRange.length)) {
        selectedRange.length = selectedRange.length + length - range.length;
        return selectedRange;
    }
    selectedRange.location = range.location + length;
    selectedRange.length = 0;
    return selectedRange;
}


- (NSAttributedString *)_attachmentWithFontSize:(CGFloat)fontSize image:(UIImage *)image shrink:(BOOL)shrink {
    
    //    CGFloat ascent = YYEmojiGetAscentWithFontSize(fontSize);
    //    CGFloat descent = YYEmojiGetDescentWithFontSize(fontSize);
    //    CGRect bounding = YYEmojiGetGlyphBoundingRectWithFontSize(fontSize);
    
    // Heiti SC 字体。。
    CGFloat ascent = fontSize * 0.86;
    CGFloat descent = fontSize * 0.14;
    CGRect bounding = CGRectMake(0, -0.14 * fontSize, fontSize, fontSize);
    UIEdgeInsets contentInsets = UIEdgeInsetsMake(ascent - (bounding.size.height + bounding.origin.y), 0, descent + bounding.origin.y, 0);
    
    YYTextRunDelegate *delegate = [YYTextRunDelegate new];
    delegate.ascent = ascent;
    delegate.descent = descent;
    delegate.width = bounding.size.width;
    
    YYTextAttachment *attachment = [YYTextAttachment new];
    attachment.contentMode = UIViewContentModeScaleAspectFit;
    attachment.contentInsets = contentInsets;
    attachment.content = image;
    
    if (shrink) {
        // 缩小~
        CGFloat scale = 1 / 10.0;
        contentInsets.top += fontSize * scale;
        contentInsets.bottom += fontSize * scale;
        contentInsets.left += fontSize * scale;
        contentInsets.right += fontSize * scale;
        contentInsets = UIEdgeInsetPixelFloor(contentInsets);
        attachment.contentInsets = contentInsets;
    }
    
    NSMutableAttributedString *atr = [[NSMutableAttributedString alloc] initWithString:YYTextAttachmentToken];
    
    [atr yy_setTextAttachment:attachment range:NSMakeRange(0, atr.length)];
    CTRunDelegateRef ctDelegate = delegate.CTRunDelegate;
    [atr yy_setRunDelegate:ctDelegate range:NSMakeRange(0, atr.length)];
    if (ctDelegate) CFRelease(ctDelegate);
    
    return atr;
}

@end
